//
//  UITextView + Extension.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/4/8.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit

extension FZBlogTextView {
    //获取富文本对应的字符串
    
    var emotionText : String {
        
        var sendMessage = ""
        //便利textView的富文本
        self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: []) { (info, range, _) in
//            info : 富文本信息 range : 富文本范围
           print(info)
            if let attachment = info["NSAttachment"] as? FZAttachMent ,let emotion = attachment.emotionModel{
                
                let chs = emotion.chs!
                sendMessage += chs
            }else{
                
                let subAttributeString = self.attributedText.attributedSubstring(from: range)
                
                let text = subAttributeString.string
                sendMessage += text
            }
            
        }
        
        return sendMessage
    }
    
    
    //根据表情模型插入表情富文本
    func insertEmotion(emotion : FZEmotionModel) {
        
        if emotion.type == "0"{
            
           let lastAttriButeStr = NSMutableAttributedString(attributedString: self.attributedText)
                    
           let attrbuterStr = NSAttributedString.attributeStringAccordingToEmotion(emotion : emotion,font : self.font!)
            
           var selectedStrRange = self.selectedRange
            
           lastAttriButeStr.replaceCharacters(in: selectedRange, with: attrbuterStr)
            
           lastAttriButeStr.addAttributes([NSFontAttributeName : self.font!], range: NSMakeRange(0, lastAttriButeStr.length))
            
           self.attributedText = lastAttriButeStr
            
           selectedStrRange.location += 1
           selectedStrRange.length = 0
            
           self.selectedRange = selectedStrRange
            
           self.delegate?.textViewDidChange?(self)
            
           NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        }else {
            
            //  emoji表情
            let emoji = (emotion.code! as NSString).emoji()!
            self.insertText(emoji)
        }
        
    }
    
    
}
